var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.VIP01;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'vip/member/page';

var Utils = {
	doQueryMemberType : function(){
		commonDia = $.dialog({
			title : '会员类别',
			content : 'url:'+config.BASEPATH+'vip/membertype/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#vm_mt_code").val(selected.mt_code);
					$("#mt_name").val(selected.mt_name);
				}
			},
			cancel:true
		});
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:true},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var sp_code = [];
				var sp_name = [];
				for(var i=0;i<selected.length;i++){
					sp_code.push(selected[i].sp_code);
					sp_name.push(selected[i].sp_name);
				}
				$("#vm_shop_code").val(sp_code.join(","));
				$("#sp_name").val(sp_name.join(","));
			},
			close:function(){
				if(commonDia.content.dblClick){
					var selected = commonDia.content.doSelect();
					var sp_code = [];
					var sp_name = [];
					for(var i=0;i<selected.length;i++){
						sp_code.push(selected[i].sp_code);
						sp_name.push(selected[i].sp_name);
					}
					$("#vm_shop_code").val(sp_code.join(","));
					$("#sp_name").val(sp_name.join(","));
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#vm_manager_code").val(selected.em_code);
					$("#vm_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	doReport:function(id){
		if(null == id || "" == id){
			Public.tips({type: 2, content : "请选择会员!"});
			return;
		}
		$.dialog({
			title : '智能分析',
			content : 'url:'+config.BASEPATH+'vip/member/to_report?vm_id='+id,
			width : 888,
			height : 545,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	queryVipMembers:function(select_member_type){
		$("#select_member_type").val(select_member_type);
		if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
			return ;
		}
		THISPAGE.reloadData();
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		var height = 520;
		var width = 810;
		if(oper == 'add'){
			title = '新增';
			url = config.BASEPATH+"vip/member/to_add";
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			title = '修改';
			url = config.BASEPATH+"vip/member/to_update?vm_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'import'){
			title = '会员批量导入';
			height = 350;
			width = 550;
			url = config.BASEPATH+"vip/member/to_import_member";
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : title,
			content : 'url:'+url,
			data: data,
			width : width,
			height : height,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'vip/member/del',
					data:{"vm_id":rowId,"vm_code":rowData.vm_code},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : '删除失败!'});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    callback: function(data, oper, dialogWin){
		var gridData = $("#grid").data('gridData');
		if(!gridData){
			gridData = {};
			$("#grid").data('gridData', gridData);
		}
		gridData[data.id] = data;
		if(oper == "edit") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		} 
		if(oper == "add"){
			$("#grid").jqGrid('addRowData', data.id, data, 'first');
		}
	},
	formatState:function(val, opt, row){//0:正常 1:无效 2:挂失
		if(val == "0"){
			return "正常";
		}else if(val == "1"){
			return "无效";
		}else if(val == "2"){
			return "挂失";
		}else{
			return val;
		}
	},
	formatBirthdayType:function(val, opt, row){//0公历生日1为农历生日
		if(val == "0"){
			return "公历";
		}else if(val == "1"){
			return "农历";
		}
		return '';
	},
	formatBirthday:function(val, opt, row){//0公历生日1为农历生日
		if(row.vm_birthday_type == "0"){
			return $.trim(row.vm_birthday);
		}else if(row.vm_birthday_type == "1"){
			return $.trim(row.vm_lunar_birth);
		}else{
			return '';
		}
	},
	operFmatter:function (val, opt, row) {
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += "<i class='iconfont i-hand' title='回访' onclick=\"handle.consumeVisit('"+row.vm_id+"','"+row.vm_cardcode+"')\" >&#xe69b;</i>";
		html_con += "<i class='iconfont i-hand ui-icon-sign' title='标签' onclick=\"handle.toSetMemberTag('"+row.vm_code+"','"+row.vm_name+"','"+row.vm_cardcode+"')\">&#xe6e1;</i>";
		html_con += '</div>';
		return html_con;
	},
	formatterTagName:function(val, opt, row){ 
		var newVal="";
		if(val!="" && val!=undefined ){
			var al=val.split(",");
			
			for(var i=0;i<al.length;i++){
				newVal+="<span style='color:#fff;border-radius:3px;font-size:12px;padding:2px 3px;background:#2894FF'>"+al[i]+"</span> &nbsp;";
			}
		}
	   return newVal;
	},
	consumeVisit:function(vm_id, vm_cardcode){//消费回访
		/*if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
			return ;
		}*/
		$.dialog({ 
		   	title:'会员回访',
		   	//data:{vi_type:3},//1:会员回访 2:生日回访 3:消费回访
		   	max: false,
		   	min: false,
		   	width:900,height:450,
		   	fixed:false,
		   	drag: true,
		   	resize:false,
		   	content:'url:'+config.BASEPATH+'vip/member/vip_visit_analysis?vm_id='+vm_id+'&vi_type=1&vm_cardcode='+vm_cardcode,
		   	lock:true,
		   	close: function(){
		   		if(isRefresh){
		   			THISPAGE.reloadData();
		   			isRefresh = false;
		   		}
		   	}
	    });
	},
	//设置标签
	toSetMemberTag:function(vm_code,vm_name,vm_cardcode){
		$.dialog({ 
			id: 'setMemberTag',
			title: '设置标签',
			max: false,
			min: false,
			width: '850px',
			height: '450px',
			fixed:false,
			drag: true,
			content:'url:'+config.BASEPATH+'vip/member/to_set_member_tag?vm_code='+vm_code+'&vm_name='+Public.encodeURI(vm_name)+'&vm_cardcode='+vm_cardcode,
			close:function(){
				if(isRefresh){
		   			THISPAGE.reloadData();
		   			isRefresh = false;
		   		}
			}
		});
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 80, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{name: 'vm_code',label:'编号',index: 'vm_code',width:0,hidden:true},
	    	{name: 'vm_cardcode',label:'卡号',index: 'vm_cardcode',width:120},
	    	{name: 'vm_name',label:'名称',index: 'vm_name',width:100},
	    	{name: 'mt_name',label:'类别',index: 'vm_mt_code',width:60},
	    	{name: 'vm_state',label:'状态',index: 'vm_state',align:'center',width:50,formatter:handle.formatState},
	    	{name: 'vm_mobile',label:'手机',index: 'vm_mobile',width:96},
	    	{name: 'vm_tag_name',label:'标签',index:'vm_tag_name',width: 140,formatter:handle.formatterTagName, title: true},
	    	{name: 'vm_sex',label:'性别',index: 'vm_sex',align:'center',width:40},
	    	{name: 'vm_birthday_type',label:'方式',index: 'vm_birthday_type',align:'center',width:60,formatter:handle.formatBirthdayType},
	    	{name: 'vm_birthday',label:'生日',index: 'vm_birthday',width:82,formatter:handle.formatBirthday},
	    	{name: 'vm_notbuy_day',label:'N天未消费',index:'vm_lastbuy_date',width: 80, title: false, align:'center'},
	    	{name: 'vm_times',label:'总次数',index: 'vm_times',width:70},
	    	{name: 'vm_total_money',label:'总金额',index: 'vm_total_money',width:70},
	    	{name: 'vm_used_points',label:'使用积分',index: 'vm_used_points',width:70},
	    	{name: 'vm_points',label:'剩余积分',index: 'vm_points',width:70},
	    	{name: 'vm_date',label:'办卡日期',index: 'vm_date',width:82},
	    	{name: 'shop_name',label:'发卡门店',index: 'vm_shop_code',width:120}
	    	/*{name: 'vm_lastbuy_date',label:'未消费',index: 'vm_lastbuy_date',width:50,align:'center',formatter:Public.days},
	    	{name: 'vm_lastbuy_money',label:'最后金额',index: 'vm_lastbuy_money',width:70}*/
	    ];
		$('#grid').jqGrid({
			datatype: 'local',
			width: gridWH.w-255,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:true,//多选
			viewrecords: true,
			rowNum:99,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'vm_id'  //图标ID
			},
			loadComplete: function(data){
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				Utils.doReport(rowid);
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&vm_mt_code='+$("#vm_mt_code").val();
		params += '&vm_shop_code='+$("#vm_shop_code").val();
		params += '&vm_manager_code='+$("#vm_manager_code").val();
		params += '&vm_cardcode='+Public.encodeURI($("#vm_cardcode").val());
		params += '&vm_name='+Public.encodeURI($("#vm_name").val());
		params += '&vm_mobile='+Public.encodeURI($("#vm_mobile").val());
		params += '&vm_tag_name='+Public.encodeURI($("#vm_tag_name").val());
		params += '&begin_total_money='+$("#begin_total_money").val();
		params += '&end_total_money='+$("#end_total_money").val();
		params += '&begin_last_points='+$("#begin_last_points").val();
		params += '&end_last_points='+$("#end_last_points").val();
		params += '&begin_notbuy_day='+$("#begin_notbuy_day").val();
		params += '&end_notbuy_day='+$("#end_notbuy_day").val();
		params += '&select_member_type='+$("#select_member_type").val();
		params += '&lossDay='+$("#lossDay").val();
		params += '&consumeDay='+$("#consumeDay").val();
		params += '&loyalVipTimes='+$("#loyalVipTimes").val();
		params += '&richVipMoney='+$("#richVipMoney").val();
		return params;
	},
	reset:function(){
		$("#vm_mt_code").val("");
		$("#vm_shop_code").val("");
		$("#vm_manager_code").val("");
		$("#vm_cardcode").val("");
		$("#vm_name").val("");
		$("#vm_mobile").val("");
		$("#mt_name").val("");
		$("#sp_name").val("");
		$("#vm_manager").val("");
		THISPAGE.$_date.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
		$("#select_member_type").val("");
		$("#vm_tag_name").val("");
		$("#begin_total_money").val("");
		$("#end_total_money").val("");
		$("#begin_last_points").val("");
		$("#end_last_points").val("");
		$("#begin_notbuy_day").val("");
		$("#end_notbuy_day").val("");
		
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			$("#select_member_type").val("");
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			$("#select_member_type").val("");
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		//修改
		$('#grid').on('click', '.operating .ui-icon-pencil', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.operate('edit', id);
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_membertype").click(function(){
			Utils.doQueryMemberType();
		});
		$("#btn_shop").click(function(){
			Utils.doQueryShop();
		});
		$("#btn_emp").click(function(){
			Utils.doQueryEmp();
		});
		$("#btn-report").click(function(){
			var id = $("#grid").jqGrid('getGridParam', 'selrow');
			Utils.doReport(id);
		});
		$('#btn-import').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.IMPORT)) {
				return ;
			};
			handle.operate('import');
		});
	}
}
THISPAGE.init();